package com.youxuit.youxu.kecheng.CASandAtomic;

import lombok.SneakyThrows;

public class PrintABCBySyn {

    private static int state = 0;

    private static Object lock = new Object();

    public static void main(String[] args) {

        Thread threadA = new Thread(() -> printContext(0,"A"));
        Thread threadB = new Thread(() -> printContext(1,"B"));
        Thread threadC = new Thread(() -> printContext(2,"C"));
        threadA.start();
        threadB.start();
        threadC.start();
    }

    @SneakyThrows
    private static void printContext(int flag, String context)  {
        for (int i = 0; i < 100; i++) {
            synchronized (lock) {
                while (state % 3  == flag) {
                    System.out.printf("\n第%s次输入,输出%s", i, context);
                    state++;
                    lock.notifyAll();
                }
                lock.wait();
            }
        }
    }
}
